import { TOKENNAME } from './../config.js';

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


/**
 * 处理服务器扫码带进来的参数
 * @param string param 扫码携带参数
 * @param string k 整体分割符 默认为：&
 * @param string p 单个分隔符 默认为：=
 * @return object
 * 
*/
const getUrlParams = (param, k, p) => {
  if (typeof param != 'string') return {};
  k = k ? k : '&';//整体参数分隔符
  p = p ? p : '=';//单个参数分隔符
  var value = {};
  if (param.indexOf(k) !== -1) {
    param = param.split(k);
    for (var val in param) {
      if (param[val].indexOf(p) !== -1) {
        var item = param[val].split(p);
        value[item[0]] = item[1];
      }
    }
  } else if (param.indexOf(p) !== -1) {
    var item = param.split(p);
    value[item[0]] = item[1];
  } else {
    return param;
  }
  return value;
}

const wxgetUserInfo = function () {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      lang: 'zh_CN',
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      }
    })
  });
}

/** 检查用户登陆情况 */
const checkLogin = function (token, isLog) {
  if (getApp()) {
    token = getApp().globalData.token;
    isLog = getApp().globalData.isLogin;
  }
  return isLog && token;
}

const chekWxLogin = function () {
  return new Promise((resolve, reject) => {
    if (checkLogin()) {
      return resolve({ userinfo: getApp().globalData.userInfo, isLogin: true });
    }
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          return reject({ authSetting: false });
        } else {
          wx.getStorage({
            key: 'cache_key',
            success(res) {
              wxgetUserInfo().then(userInfo => {
                userInfo.cache_key = res.data;
                return resolve({ userInfo: userInfo, isLogin: false });
              }).catch(res => {
                return reject(res);
              });
            },
            fail() {
              getCodeLogin((res) => {
                wxgetUserInfo().then(userInfo => {
                  userInfo.code = res.code;
                  return resolve({ userInfo: userInfo, isLogin: false });
                }).catch(res => {
                  return reject(res);
                })
              });
            }
          })

        }
      },
      fail(res) {
        return reject(res);
      }
    })
  })
}

/**　退出登陆 */
const logout = function () {
  getApp().globalData.token = '';
}

/**
 * 
 * 授权过后自动登录
*/
const autoLogin = function () {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: 'cache_key',
      success(res) {
        wxgetUserInfo().then(userInfo => {
          userInfo.cache_key = res.data;
          return resolve(userInfo);
        }).catch(res => {
          return reject(res);
        })
      },
      fail() {
        getCodeLogin((code) => {
          wxgetUserInfo().then(userInfo => {
            userInfo.code = code.code;
            return resolve(userInfo);
          }).catch(res => {
            return reject(res);
          })
        });
      }
    });
  })
}

const getCodeLogin = function (successFn) {
  wx.login({
    success(res) {
      successFn(res);
    }
  })
}

module.exports = {
  formatTime: formatTime,
  getUrlParams: getUrlParams,
  chekWxLogin: chekWxLogin,
  getCodeLogin: getCodeLogin,
  checkLogin: checkLogin,
  wxgetUserInfo: wxgetUserInfo,
  autoLogin: autoLogin,
  logout: logout
}
